package com.dai.zhenfujin.issue.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.ResultBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.my.activity.ReleaseActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.CustomLoadingDialog;
import com.dai.zhenfujin.visitingcard.app.LocationActiviy;
import com.orhanobut.logger.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;


public class AlumIssueActivity2 extends BaseActivity implements View.OnClickListener, BGASortableNinePhotoLayout.Delegate {
    private TextView tvName, et_type, tv_price, tv_leibie,tv_chanping,et_address;
    private ImageView title_imageview;
    private FrameLayout fl_alum, fl_img;
    private EditText et_name, et_price, et_info;
    private BGASortableNinePhotoLayout mPhotosSnpl;

    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;
    private List<String> data;
    private OSS oss;
    private ArrayList<String> list_path = new ArrayList<>();
    private boolean flag;
    private ProListBean.ProListBean2 bean;
    private List<String> mImgUrls;
    private int type;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alum_issue_activity2);
        tvName = findViewById(R.id.title_textview);
        fl_alum = findViewById(R.id.fl_alum);
        fl_img = findViewById(R.id.fl_img);
        et_name = findViewById(R.id.et_name);
        et_price = findViewById(R.id.et_price);
        et_address = findViewById(R.id.et_address);
        et_info = findViewById(R.id.et_info);
        et_type = findViewById(R.id.et_type);
        tv_chanping = findViewById(R.id.tv_chanping);
        mPhotosSnpl = findViewById(R.id.snpl_moment_add_photos);
        tv_price = findViewById(R.id.tv_price);
        tv_leibie = findViewById(R.id.tv_leibie);  //类别
        fl_alum.setVisibility(View.VISIBLE);
        initData();
        initListener();
    }

    private void initListener() {
        fl_img.setOnClickListener(this);
        fl_alum.setOnClickListener(this);
        mPhotosSnpl.setDelegate(this);
        et_address.setOnClickListener(this);
    }

    private void initData() {
        type = getIntent().getIntExtra("type", 0);
        if (type == 3) {
            String userId = SPUtils.getString(this,Constants.USER_MOBILE);
            tvName.setText(SPUtils.getConversionUserJob(this, userId));
        } else {
            tvName.setText(getIntent().getStringExtra("name"));
        }

        bean = (ProListBean.ProListBean2) getIntent().getSerializableExtra("bean");
        if (type == 1) {
            tv_price.setText("年收入");
            tv_leibie.setText("性别");
            tv_chanping.setText("个人介绍");
        }else if (type == 3){
            tv_leibie.setText("主业");
            tv_chanping.setText("标签");
        }else if (type == 2){
            tv_leibie.setText("副业");
            tv_chanping.setText("标签");
        }

        if (bean != null) {
            et_name.setText(bean.getPro_name());
            et_price.setText(bean.getPro_price());
            tvName.setText(bean.type_name);
            et_address.setText(bean.getPro_address());
            et_info.setText(bean.getPro_info());
            mImgUrls = bean.url_list;
            if (mImgUrls != null && mImgUrls.size() > 0)
                mPhotosSnpl.addMoreData((ArrayList<String>) mImgUrls);
            list_path.clear();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_address:
                Intent company_address = new Intent(this, LocationActiviy.class);
                company_address.putExtra("type", 0);
                startActivityForResult(company_address, 5);
                break;
            case R.id.fl_alum: //地址
                if (TextUtils.isEmpty(et_name.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入标题");
                    return;
                }
               /* if (TextUtils.isEmpty(et_price.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入价格");
                    return;
                }*/
               /* if (TextUtils.isEmpty(et_type.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入类别");
                    return;
                }*/
               /* if (TextUtils.isEmpty(et_address.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入地址");
                    return;
                }*/
               /* if (TextUtils.isEmpty(et_info.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入产品介绍");
                    return;
                }*/

                if (mPhotosSnpl != null && mPhotosSnpl.getData().size() > 0) {
                    if (UIUtils.isFastClick())
                        CustomLoadingDialog.show(this);
                    submitImg();
                } else {
                    UIUtils.showToastSafe("请先添加图片");
                }

                break;
            case R.id.fl_img:
                finish();
                break;
        }
    }

    private void submitImg() {
        int totalNum = 0;
        data = mPhotosSnpl.getData();
        if (flag) {
            submit();
        }
        initOss(); //配置OSS
        for (String datum : data) {
            if (!datum.startsWith("https:")) {
                ossToken(revitionImageSize(datum));
            } else {
                flag = false;
                list_path.add(datum);
            }
        }

        if (list_path != null) {
            for (String s : list_path) {
                if (s.startsWith("https:")) {
                    totalNum += 1;
                }
            }
        }

        if (totalNum == mPhotosSnpl.getData().size()) {
            flag = false;
            submit();
        }
    }

    private void initOss() {
        String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        //   OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.ACCESS_ID, Constants.ACCESS_KEY);

        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    }


    int number;

    private void ossToken(String path) {
        // 判断图片是否全部上传
        // 如果已经是最后一张图片上传成功，则跳出
        number++;
        if (number > data.size()) {
            // 结束的处理逻辑，并退出该方法
            return;
        }

        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("zenfujin-bucket", "products/" + imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                list_path.add("https://image.zhenfujin.net/" + "products/" + imgName + ".jpg");
                Logger.i(list_path.toString());
                if (list_path.size() == data.size())
                    runOnUiThread(() -> submit());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("onFailure", serviceException.getErrorCode());
                    Log.e("onFailure", serviceException.getRequestId());
                    Log.e("onFailure", serviceException.getHostId());
                    Log.e("onFailure", serviceException.getRawMessage());
                    UIUtils.showToastSafe("图片上传失败，请重新上传");
                }
            }
        });
    }

    private void submit() {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> params2 = new HashMap<>();
        params2.put("pro_name", et_name.getText().toString().trim());

        if (TextUtils.isEmpty(et_price.getText().toString().trim())){
            params2.put("pro_price", "");
        }else {
            params2.put("pro_price", et_price.getText().toString().trim());
        }

        if (TextUtils.isEmpty(et_address.getText().toString().trim())){
            params2.put("pro_address", "");
        }else {
            params2.put("pro_address", et_address.getText().toString().trim());
        }
        params2.put("pro_desc", et_info.getText().toString().trim());
        if(list_path.size() == 0){
            return;
        }
        params2.put("flie_list", list_path);
        if (null != bean) { //修改
            params2.put("pro_id", bean.getPro_id());
        } else {
            if (type == 3) { //名片ID，该ID有值时为修改，没有值为新增
                params2.put("pro_id", "");
            } else {
                params2.put("pro_id", "");
            }
        }

        if (!TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            params2.put("type_id", getIntent().getStringExtra("id"));  //类别
        } else {  //Constants.TYPE_ID
            params2.put("type_id", SPUtils.getString(AlumIssueActivity2.this,Constants.TYPE_ID));  //分类类别
        }

        params.put("req_bd", params2);
        Logger.i("submit-----" + list_path.toString());
        HttpClient.post(AlumIssueActivity2.this, Constants.EDITPRODUCT, params, new CallBack<ResultBean>() {
            @Override
            public void onSuccess(ResultBean resultBean) {
                CustomLoadingDialog.dismiss(AlumIssueActivity2.this);
                if (resultBean.res_code == 510) {
                    flag = true;
                    startActivity(new Intent(AlumIssueActivity2.this, ReleaseActivity.class));
                    finish();
                } else {
                    UIUtils.showToastSafe("等待审核");
                    CustomLoadingDialog.dismiss(AlumIssueActivity2.this);
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.UPDATA_PRODUCT_LIST);
                  //  EventBus.getDefault().post(messageEvent);
                    finish();
                }
            }
        });
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    private void choicePhotoWrapper() {
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "zhen");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        if (mPhotosSnpl.getData().size() > 1) {
            mPhotosSnpl.removeItem(position);
            if(null != mImgUrls && mImgUrls.size() > 1)
            mImgUrls.remove(position);
        } else {
            UIUtils.showToastSafe("请至少保留一张图片在提交");
        }
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) { //拍照
            mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));

        } else if (requestCode == RC_PHOTO_PREVIEW) {   //相册
            mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
        } else if (requestCode == 5 && resultCode == -1){
            String address = data.getStringExtra("address");
            et_address.setText(address);
        }
    }


    private String revitionImageSize(String path) {
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; //只读取图片，不加载到内存中
            BitmapFactory.decodeStream(in, null, options);
            in.close();

            options.inJustDecodeBounds = false;
            int w = options.outWidth;
            int h = options.outHeight;
            float hh = 800f;//
            float ww = 480f;//
            int be = 1;
            if (w > h && w > ww) {
                be = (int) (options.outWidth / ww);
            } else if (w < h && h > hh) {
                be = (int) (options.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            options.inSampleSize = be;//设置采样率

            options.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
            options.inPurgeable = true;// 同时设置才会有效
            options.inInputShareable = true;//。当系统内存不够时候图片自动被回收

           /* int i = 0;
            // options.inJustDecodeBounds=true那么将不返回实际的bitmap对象，不给其分配内存空间但是可以得到一些解码边界信息即图片大小等信息
            // outHeight(图片原始高度)和 outWidth(图片的原始宽度)
            // inSampleSize表示缩略图大小为原始图片大小的几分之一
            // options.outWidth >> i(右移运算符)表示：outWidth/(2^i)
            while (true) {
                if ((options.outWidth >> i <= 500)
                        && (options.outHeight >> i <= 500)) {
                    in = new BufferedInputStream(
                            new FileInputStream(new File(path)));
                    options.inSampleSize = (int) Math.pow(2.0D, i); // 幂运算 i为几次方
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    break;
                }
                i += 1;
            }*/
            String newPath = Constants.APP_FOLD + path.substring(path.lastIndexOf("/"));
            saveBitmapToFile(bitmap, newPath);
            // bitmap = BitmapFactory.decodeFile(path, options);
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param _file
     * @throws IOException
     */
    public void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
